import {observable, action, /*toJS*/} from 'mobx';
import {Toast,Tools,Modal} from 'weaver-mobile';
import * as API from '../../api/attach';
import * as API_netdisk from '../../api/netdisk'
import {SetTitle,attachAlert,downloadFile} from '../../util/Utils'
import {toJS} from 'mobx';

const getLabel = Tools.getLabel;

export default class AttachStore {
    @observable isConvertFileEnd = false;
    @observable openAttachPath = '';
    @observable isConvertFileSuccess = false;
    @observable imgInited = false;  //图片列表是否加载完成
    @observable imgList = []; //图片列表
    @observable imgVisible = false;  //是否展示图片
    @observable imgIndex = 0; //展示第几张图片
    @observable fileName= ''; //文件名
    @observable canReader = true; //判断当前的云盘目录是否可以访问
    @observable shareCancle = false; //分享被取消
    @observable fileDel = false; //文件被删除
    @observable convertMessage = ""; //转换失败后的返回信息 
    @observable otherMouldUrlParams = '';//其他模块传过来的参数
    @observable isReadOnline = '0'; //判断当前打开的附件是否可以在线预览
    @observable docInfo; //当前附件所在文档的信息
    @observable attachInfo; //当前附件的信息
    @observable loading = true;
    @observable isUsePoi = false;
    @observable docisLock = false;
    secWmSet = {};
    @observable fromModule="";

    
    @action
    init = (params,that) =>{
        let resource = params && (params.resource ||'');
        let fid = params && (params.fid ||'');
        let type = params && (params.type ||'');
        let fileid = params && (params.fileid ||'');
        if(resource === 'em' && type === 'file'){
          this.getShareIsReader({fid,type}).then(()=>{
              if(this.canReader){
                this.isConvertFileEnd = false;
                this.convertFile({fileid:fileid,resource:"netdisk"});
                SetTitle(this.fileName,getLabel(129207, '我的云盘'),that);
              }
          })
        }
    }
    setDocLockStore = () =>{
        try{
            const {docStore} = this.props;
            let iframeList = document.getElementsByTagName("iframe");
			if(docStore.docisLock){
		    document.body.style.cssText += ';-moz-user-select: none;-webkit-user-select: none;-ms-user-select: none;-khtml-user-select: none;user-select: none;unselectable:on;';
            document.body.onselectstart = function () {return false};
			  for(let index =0;index < iframeList.length; index++){
                let domNode = iframeList && iframeList[index].contentWindow.document;
                  if (!domNode) return;
                  if(domNode.body){
                   domNode.body.style.cssText += ';-moz-user-select: none;-webkit-user-select: none;-ms-user-select: none;-khtml-user-select: none;user-select: none;unselectable:on;';
                   domNode.body.onselectstart = function () {return false};
                 }
			  }
			}
         } catch(e){
        // 防止跨域报错
         }
    }
    fileToDocDetail = (params,_this) =>{
        const isiPhone = Tools.mobileDetect().is('iPhone');
        let fileid = params.fileid || "";
        let chagneTopTitle = (params && params.chagneTopTitle) ? params.chagneTopTitle : "true";
        this.loading = true;
        API.fileToDocDetail({fileid}).then((result)=>{
            this.canReader = result.canReader || false;
            this.docisLock = result.docisLock || false;
			if(this.docisLock){
		      setTimeout(() => {
                this.setDocLockStore();
              },1);
            }
            if(this.canReader && !result.hasDoc){
                let fileInfo = result.fileInfo;
                this.isReadOnline = fileInfo.readOnLine;
                this.attachInfo = fileInfo;
                this.docInfo = fileInfo;
                let ddcode = fileInfo.ddcode || "";
                let fileurl = `/weaver/weaver.file.FileDownload?fileid=${fileInfo.imagefileid}&download=1&from_doc_mobile=1`;
                //钉钉与em7集成，下载附件丢失session解决方法
                if(ddcode){
                    fileurl = fileurl + `&ddcode=${ddcode}`
                }
                 //其他模块传过来的参数
                if(this.otherMouldUrlParams){
                    fileurl = fileurl + `&${this.otherMouldUrlParams}`
                }
                if(this.isReadOnline === "1"){
                    let attachtype = fileInfo.ficon.iconType;
                    if(attachtype === 'pdf' && isiPhone && fileInfo.doc_pdf_download === "1"){
                        downloadFile(fileurl,fileInfo.imagefileid);
                    }else{
                        this.convertFile({fileid});
                    }
                }else{
                    attachAlert(fileInfo,fileInfo,fileurl)
                }
            }
            if(this.canReader && result.hasDoc){
                this.secWmSet = result.secWmSet;
                if(result.secWmSet.isopenwater !== '1' || result.secWmSet.wmforview !== '1'){
                    this.isShowWater = false;
                    setTimeout(function(){
                    if(window.waterMark){
                        window.waterMark.destory();
                    }
                    },1);
                }
                let attachList = [];
                let attach;
                this.docInfo = result.docInfo;
                if(result.docInfo && result.docInfo.docAttrs ){
                    attachList = result.docInfo.docAttrs;
                }
                attachList.forEach(element => {
                    if(element.imagefileid === fileid){
                        attach = element;
                    }
                    if((toJS(this.fromModule)==="meeting" || toJS(this.fromModule)==="workplan")){
                        attach = element;
                        fileid = attach.imagefileid;
                    }
                });
                chagneTopTitle!="false" && SetTitle(attach.filename,getLabel(83124,"查看附件"),_this);
                this.attachInfo = attach;
                this.isReadOnline = attach.readOnLine || '0';
                let ddcode = attach.ddcode || "";
                let fileurl = `/weaver/weaver.file.FileDownload?fileid=${attach.imagefileid}&download=1&from_doc_mobile=1`;
                //钉钉与em7集成，下载附件丢失session解决方法
                if(ddcode){
                    fileurl = fileurl + `&ddcode=${ddcode}`
                }
                 //其他模块传过来的参数
                if(this.otherMouldUrlParams){
                    fileurl = fileurl + `&${this.otherMouldUrlParams}`
                }
                if(this.isReadOnline === "1"){
                    let attachtype = attach.ficon.iconType;
                    if(attachtype === 'pdf' && isiPhone && result.docInfo.doc_pdf_download === "1"){
                        downloadFile(fileurl,attach.imagefileid);
                    }else{
                        this.convertFile({fileid});
                    }
                }else{
                    attachAlert(attach,result.docInfo,fileurl)
                }
            }
            this.loading = false;
        });
    }
    //附件转换
    @action
    convertFile = (params) =>{
        const isiPhone = Tools.mobileDetect().is('iPhone');
        API.isPicture({fileid:params.fileid}).then((ans)=>{
            let ispic = ans.ispic,url = `/weaver/weaver.file.FileDownload`,
            ReadOnline = ans.readOnLine,fileurl="";
            let resource = (params && params.resource) ? params.resource : "";
            fileurl = `/weaver/weaver.file.FileDownload?fileid=${params.fileid}&download=1`;
            if((ispic==="0" && resource === "") || (ispic==="0" && resource === "netdisk" && ReadOnline === "1")){
                Toast.loading(getLabel(390467,'正在转换中...'),0);
            }
            if(ReadOnline === "0" && resource === "netdisk"){
                this.alertDownload(ans.downloadurl,params.fileid,ans);
            } else{
                this.isConvertFileEnd = false;
                API.convertFile({convertFile:'html',fileid:params.fileid}).then(res => {
                    const { result, data, message,convert } = res;
                    ispic === "0" && Toast.hide();
                    if("system"===convert){
                        this.isUsePoi = true;
                        let convertId = "",status=0;
                        convertId = res.convertId;
                        status = res.status;
                        if(status===1){
                            this.isConvertFileSuccess = true;
                            if(isiPhone){
                                url = url + `?fileid=${params.fileid}&download=1`
                            }else{
                                url = url + `?fileid=${convertId}`
                            }
                            
                            if(this.otherMouldUrlParams){
                                url = url + `&${this.otherMouldUrlParams}`
                            }
                            this.openAttachPath = url;
                        }else{
                            this.isConvertFileSuccess = false;
                            this.convertMessage = "转换失败";
                        }
                    }else{
                        if(result===0){
                            this.openAttachPath = data && data[0].path ? data[0].path : '';
                            let flag = this.openAttachPath.indexOf("spa/document/index2mobile");
                            if(flag<0){
                                flag = this.openAttachPath.indexOf("docs/pdfview/web/pdfViewer");
                            }
                            this.openAttachPath = (flag>0 && this.otherMouldUrlParams) ? (this.openAttachPath + (this.openAttachPath.indexOf('?')>0 ? '&' : '?')+this.otherMouldUrlParams):this.openAttachPath;
                            this.isConvertFileSuccess = true;
                        }else{
                            this.isConvertFileSuccess = false;
                            this.convertMessage = message;
                        }
                    }
                    this.isConvertFileEnd = true;
                });
            }
            
        });
    }

     // 弹出下载的提示框
    alertDownload = (fileurl,officeImagefileid,docInfo) =>{
        docInfo.doc_acc_download_noalert === "1"
        ? Modal.alert(getLabel(24960,'提示信息'), getLabel(391350, "您查看的文档不能直接打开,是否下载查看?"), [
            { text: getLabel(31129, '取消')},
            { text: getLabel(826, '确定'), onPress: () => {
            downloadFile(fileurl,officeImagefileid);
            }
            },
        ])
        :downloadFile(fileurl,officeImagefileid);
    }
    //获取文件的名称以及查看权限
    getShareIsReader = (params) =>{
        return API_netdisk.checkShare(params).then((result) =>{
            if(result){
                this.canReader = result.canReader;
                this.shareCancle = result.shareCancle;
                this.fileDel = result.fileDel;
                this.fileName = result.fileName || '';
            } 
        });
    }
    setImgList = (imgList) => {
        this.imgList = imgList;
        this.imgInited = true;
    }
    
    openImg = (index) => {
        this.imgIndex = index;
        this.imgVisible = true;
    }
    
    closeImg = () => {
        this.imgVisible = false;
    }
    
    updateImg = (index, newProps) => {
        let imgList = toJS(this.imgList);
        if (index < 0 || index > imgList.length) {
            return;
        }
        imgList[index] = {...imgList[index], ...newProps};
        this.imgList = [...imgList];
    }

    getDownloadParams = (params) =>{
        return API.getDownloadParams(params);
    }
}
